package com.papercutting.platform.service.impl;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import com.papercutting.platform.dto.request.AIChatRequest;
import com.papercutting.platform.dto.response.AIChatResponse;
import com.papercutting.platform.exception.BusinessException;
import com.papercutting.platform.service.AIService;
import io.reactivex.Flowable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * AI服务实现类
 */
@Slf4j
@Service
public class AIServiceImpl implements AIService {
    
    @Value("${app.ai.qwen.api-key}")
    private String apiKey;
    
    @Value("${app.ai.qwen.model:qwen-plus}")
    private String model;
    
    @Value("${app.ai.qwen.system-prompt}")
    private String systemPrompt;
    
    private Generation generation;
    
    @PostConstruct
    public void init() {
        // 初始化通义千问客户端
        generation = new Generation();
        log.info("通义千问AI服务初始化成功，模型: {}", model);
    }
    
    @Override
    public AIChatResponse chat(AIChatRequest request) {
        try {
            // 构建消息列表
            List<Message> messages = new ArrayList<>();
            
            // 添加系统提示词
            messages.add(Message.builder()
                    .role(Role.SYSTEM.getValue())
                    .content(systemPrompt)
                    .build());
            
            // 添加历史对话
            if (request.getHistory() != null && !request.getHistory().isEmpty()) {
                for (AIChatRequest.ChatMessage historyMsg : request.getHistory()) {
                    messages.add(Message.builder()
                            .role(historyMsg.getRole())
                            .content(historyMsg.getContent())
                            .build());
                }
            }
            
            // 添加用户当前消息
            messages.add(Message.builder()
                    .role(Role.USER.getValue())
                    .content(request.getMessage())
                    .build());
            
            // 构建请求参数
            GenerationParam param = GenerationParam.builder()
                    .apiKey(apiKey)
                    .model(model)
                    .messages(messages)
                    .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                    .topP(0.8)
                    .enableSearch(true) // 启用搜索增强
                    .build();
            
            // 调用通义千问API
            log.debug("发送AI请求，消息: {}", request.getMessage());
            GenerationResult result = generation.call(param);
            
            // 提取AI回复
            String reply = result.getOutput().getChoices().get(0).getMessage().getContent();
            log.debug("收到AI回复，长度: {}", reply.length());
            
            // 构建响应
            return AIChatResponse.builder()
                    .reply(reply)
                    .conversationId(result.getRequestId())
                    .build();
                    
        } catch (NoApiKeyException e) {
            log.error("API Key未配置", e);
            throw new BusinessException("AI服务配置错误，请联系管理员");
        } catch (InputRequiredException e) {
            log.error("请求参数不完整", e);
            throw new BusinessException("请求参数不完整");
        } catch (ApiException e) {
            log.error("调用通义千问API失败", e);
            throw new BusinessException("AI服务暂时不可用，请稍后重试");
        } catch (Exception e) {
            log.error("AI对话处理异常", e);
            throw new BusinessException("AI对话处理失败: " + e.getMessage());
        }
    }
    
    @Override
    public SseEmitter streamChat(AIChatRequest request) {
        // 创建SSE发射器，超时时间5分钟
        SseEmitter emitter = new SseEmitter(5 * 60 * 1000L);
        
        try {
            // 构建消息列表
            List<Message> messages = new ArrayList<>();
            
            // 添加系统提示词
            messages.add(Message.builder()
                    .role(Role.SYSTEM.getValue())
                    .content(systemPrompt)
                    .build());
            
            // 添加历史对话
            if (request.getHistory() != null && !request.getHistory().isEmpty()) {
                for (AIChatRequest.ChatMessage historyMsg : request.getHistory()) {
                    messages.add(Message.builder()
                            .role(historyMsg.getRole())
                            .content(historyMsg.getContent())
                            .build());
                }
            }
            
            // 添加用户当前消息
            messages.add(Message.builder()
                    .role(Role.USER.getValue())
                    .content(request.getMessage())
                    .build());
            
            // 构建流式请求参数
            GenerationParam param = GenerationParam.builder()
                    .apiKey(apiKey)
                    .model(model)
                    .messages(messages)
                    .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                    .topP(0.8)
                    .enableSearch(true)
                    .incrementalOutput(true) // 启用增量输出
                    .build();
            
            log.debug("发送流式AI请求，消息: {}", request.getMessage());
            
            // 使用响应式流处理
            Flowable<GenerationResult> flowable = generation.streamCall(param);
            AtomicReference<String> fullContent = new AtomicReference<>("");
            
            flowable.subscribe(
                result -> {
                    try {
                        // 提取增量内容
                        String deltaContent = result.getOutput().getChoices().get(0).getMessage().getContent();
                        fullContent.set(fullContent.get() + deltaContent);
                        
                        // 发送增量数据到前端
                        emitter.send(SseEmitter.event()
                                .name("message")
                                .data(deltaContent));
                        
                        log.trace("发送流式数据块，长度: {}", deltaContent.length());
                    } catch (IOException e) {
                        log.error("发送SSE数据失败", e);
                        emitter.completeWithError(e);
                    }
                },
                error -> {
                    log.error("流式AI调用失败", error);
                    try {
                        emitter.send(SseEmitter.event()
                                .name("error")
                                .data("AI服务暂时不可用，请稍后重试"));
                    } catch (IOException e) {
                        log.error("发送错误消息失败", e);
                    }
                    emitter.completeWithError(error);
                },
                () -> {
                    try {
                        // 发送完成信号
                        emitter.send(SseEmitter.event()
                                .name("done")
                                .data("[DONE]"));
                        emitter.complete();
                        log.debug("流式AI回复完成，总长度: {}", fullContent.get().length());
                    } catch (IOException e) {
                        log.error("发送完成信号失败", e);
                        emitter.completeWithError(e);
                    }
                }
            );
            
        } catch (NoApiKeyException e) {
            log.error("API Key未配置", e);
            try {
                emitter.send(SseEmitter.event()
                        .name("error")
                        .data("AI服务配置错误，请联系管理员"));
            } catch (IOException ex) {
                log.error("发送错误消息失败", ex);
            }
            emitter.completeWithError(e);
        } catch (Exception e) {
            log.error("流式AI对话处理异常", e);
            try {
                emitter.send(SseEmitter.event()
                        .name("error")
                        .data("AI对话处理失败: " + e.getMessage()));
            } catch (IOException ex) {
                log.error("发送错误消息失败", ex);
            }
            emitter.completeWithError(e);
        }
        
        return emitter;
    }
}

